package com.tool;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
@Component
@Aspect
public class TranseactionManger {
    @Pointcut("execution(public * com.service.AccountserviceImpl" +
            ".tranfer(..))")
    public void dt1(){};
    @Autowired
    private Connecttool connecttool;

    public void setConnecttool(Connecttool connecttool) {
        this.connecttool = connecttool;
    }
    public void begin(){
        try {
            System.out.println("Before");
            connecttool.gettreadconnect().setAutoCommit(false);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    public void commit(){
        try {
            System.out.println("AfterReturning");
            connecttool.gettreadconnect().commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    public void rollback(){
        try {
            System.out.println("AfterThrowing");
            connecttool.gettreadconnect().rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    public void release(){
        try {

            System.out.println("after");
            connecttool.gettreadconnect().close();
            connecttool.removeconnect();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    @Around(value = "dt1()")
    public Object around(ProceedingJoinPoint point)
    {
        Object value=null;
        try {
            connecttool.gettreadconnect().setAutoCommit(false);
            System.out.println("Before");
            Object[]args=point.getArgs();
            value=point.proceed(args);
            System.out.println("AfterReturning");
            connecttool.gettreadconnect().commit();
            return value;
        } catch (Throwable throwable) {
            try {
                System.out.println("AfterThrowing");
                connecttool.gettreadconnect().rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            throw new RuntimeException("你好");
        }
        finally {
            System.out.println("after");
            try {
                connecttool.gettreadconnect().close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            connecttool.removeconnect();
        }
    }
}
